<?php
// @formatter:off
/**
 * @file service.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-05-13 04:08:49 +0000 (Mon, 13 May 2013) $
 *
 * $Id: service.php 64 2013-05-13 04:08:49Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0.0.1/service.php $
 */
// @formatter:on

define('__SERVICE__', true);

require_once dirname(__FILE__).'/config/config.php';

$wcServiceXML = "";

$wcServiceStatus = false;
$wcServiceErrorCode = false;
$wcServiceErrorMsg = "unknown error";
$wcServiceXMLResult = "";

function wcServiceBuildMessage() {
	global $wcServiceXML;
	global $wcServiceAsXML;

	global $wcServiceStatus;
	global $wcServiceErrorCode;
	global $wcServiceErrorMsg;
	global $wcServiceXMLResult;

	$wcServiceXML .= "<?xml version=\"1.0\"?>";
	$wcServiceXML .= "<wc-service>";

	if(isset($_REQUEST["transaction"])) {
		$wcServiceXML .= "<wc-transaction>{$_REQUEST["transaction"]}</wc-transaction>";
	}

	if($wcServiceStatus) {
		$wcServiceXML .= "<wc-success/>";
		$wcServiceXML .= "<wc-result>{$wcServiceXMLResult}</wc-result>";
	} else {
		$wcServiceXML .= "<wc-failed/>";
		$wcServiceXML .= "<wc-error>";
		if($wcServiceErrorCode) {
			$wcServiceXML .= "<wc-code>{$wcServiceErrorCode}</wc-code>";
		}
		$wcServiceXML .= "<wc-message>{$wcServiceErrorMsg}</wc-message>";
		$wcServiceXML .= "</wc-error>";
	}

	$wcServiceXML .= "</wc-service>";

	return $wcServiceXML;
}
if(!defined("WC_NOT_INSTALLED")) {
	$timer = WCTimer::Instance();
	$timer->startGlobal();

	require_once "{$wcPaths['includes-directory']}/dynamic.conf.php";
	require_once "{$wcPaths['includes-directory']}/tools.php";

	if($_SERVER["REQUEST_METHOD"] == "POST") {
		$wcPageCache->disabled();
	}

	$cacheId = "SERVICE";
	if($wcAction) {
		if(isset($wcServicesHandlers[$wcAction])) {
			$noCache = false;
			if($wcPageCache->get($cacheId) === false) {
				if(is_readable($wcServicesHandlers[$wcAction])) {
					include $wcServicesHandlers[$wcAction];
				} else {
					$noCache = true;
					$wcServiceErrorCode = 500;
					$wcServiceErrorMsg = "Service handler unreadable";
				}

				$wcPageCache->append($cacheId, wcServiceBuildMessage());
				if(!$noCache) {
					$wcPageCache->save($cacheId);
				}
			}

			echo $wcPageCache->get($cacheId);
		} elseif($wcAction == WC_PAGEERROR_403) {
			$wcServiceErrorCode = 403;
			$wcServiceErrorMsg = "403: Access denied";
			echo wcServiceBuildMessage();
		} elseif($wcAction == WC_PAGEERROR_500) {
			$wcServiceErrorCode = 500;
			$wcServiceErrorMsg = "500: Internal failure";
			echo wcServiceBuildMessage();
		} else {
			$wcServiceErrorCode = 404;
			$wcServiceErrorMsg = "Unknown service handler";
			echo wcServiceBuildMessage();
		}
	} else {
		$wcServiceErrorCode = 500;
		$wcServiceErrorMsg = "Wrong parameters for service";
		echo wcServiceBuildMessage();
	}

	$timer->saveGlobal($cacheId);
} else {
	$wcServiceErrorCode = 500;
	$wcServiceErrorMsg = "System is not installed";
	echo wcServiceBuildMessage();
}
?>